<?php
/************************************************************************
 Omnitrix - PHP Development Framework
 Copyright (C) 2012-2018 amonest(eastson@outlook.com)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
************************************************************************/

class admin_controller_session extends omnitrix_controller
{
	public function index_action()
	{
		//
	}

	public function login_action()
	{
		if (otx_request_is_post()) {
			$username = otx_param_string('username');
			$password = otx_param_string('password');

			$x = otx_string_crypt($password);

			$ret_code = otx_session_login($username, $password);
			if ($ret_code === null) {
				otx_admin_flash_message($this->_('text_success_login', $username));
				otx_admin_log_action($this->_('text_success_login', $username));
				otx_router_redirect('index', 'dashboard', 'admin');
			} else if ($ret_code == -1) {
				otx_admin_flash_warning($this->_('error_invalid_username'));
			} else if ($ret_code == -2) {
				otx_admin_flash_warning($this->_('error_invalid_status'));
			} else if ($ret_code == -3) {
				otx_admin_flash_warning($this->_('error_invalid_password'));
			} else {
				otx_admin_flash_warning($this->_('error_login_failured'));
			}
		} else {
			$username = '';
			$password = '';
		}

		$form_wrapper = otx_html_create_wrapper(null, null, $this->_('button_login'));
		$form_table = $form_wrapper->create_table($this->_('heading_login'));
		$form_table->set_id('login');

		$form_table->add_body_row();
		$form_table->set_body_cell($this->_('entry_username'));
		$form_table->set_body_cell(otx_html_form_text('username', $username));

		$form_table->add_body_row();
		$form_table->set_body_cell($this->_('entry_password'));
		$form_table->set_body_cell(otx_html_form_password('password', $password));

		otx_html_response_title($this->_('heading_login'));
	}

	public function logout_action()
	{
		otx_admin_flash_message($this->_('text_success_logout', otx_session_user_name()));
		otx_admin_log_action($this->_('text_success_logout', otx_session_user_name()));
		otx_session_logout();
		otx_router_redirect('login');
	}
}